package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.cart.client.FeignCartClient;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author BrookPeng
 * @Date 2020/12/10 17:20
 * @Version 1.0
 *
 * 结算
 */
@Controller
public class TradeController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private FeignCartClient feignCartClient;

    @GetMapping("/trade.html")
    public String trade(Model model) {

        // 收货人地址集合 根据用户ID 用户微服务调用
        List<UserAddress> userAddressList = userFeignClient.findUserAddressList();
        model.addAttribute("userAddressList", userAddressList);
        // 订单号 (交易号) (防止重复提交) 称作幂等性问题
        // TODO
        // 商品清单
        List<CartInfo> cartCheckedList = feignCartClient.getCartCheckedList();
        List<OrderDetail> orderDetails = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            return orderDetail;
        }).collect(Collectors.toList());
        model.addAttribute("detailArrayList", orderDetails);
        // 总件数
        long sum = cartCheckedList.stream().collect(
                Collectors.summarizingInt(CartInfo::getSkuNum)).getSum();
        model.addAttribute("totalNum", sum);
        // 总金额
        BigDecimal totalPrice = new BigDecimal("0");
        for (CartInfo cartChecked : cartCheckedList) {
            totalPrice = totalPrice.add(cartChecked.getSkuPrice().multiply(new BigDecimal(cartChecked.getSkuNum())));
        }
        model.addAttribute("totalAmount", totalPrice);

        return "order/trade";
    }
}